<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header">
        <span>&nbsp;编辑商品信息&nbsp;</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack()"><i class="el-icon-arrow-left" />返回商品列表</el-button>
      </div>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" size="small" style="margin-top: 10px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="temp.productName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="商品简介" prop="productDesc">
          <el-input v-model="temp.productDesc" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" style="width: 450px" />
        </el-form-item>
        <el-form-item label="产地省份" prop="productProv">
          <el-input v-model="temp.productProv" style="width: 300px" />
        </el-form-item>
        <el-form-item label="选择分类" prop="typeId">
          <el-select v-model="temp.typeId" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in typeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="消耗积分" prop="originPrice">
          <el-input v-model="temp.originPrice" style="width: 300px" />
          <span style="font-size: small; color: gray"> * 该价格仅用于列表展示，实际价格见细分规格</span>
        </el-form-item>
        <el-form-item label="运费（元）" prop="deliverPrice">
          <el-input v-model="temp.deliverPrice" style="width: 300px" />
        </el-form-item>
        <el-form-item label="规格类型" prop="attributes">
          <el-input v-model="temp.attributes" style="width: 300px" />
        </el-form-item>
        <el-form-item label="售卖单位" prop="unit">
          <el-input v-model="temp.unit" style="width: 300px" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="temp.tags" style="display: none" />
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            type="success"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label="是否上架" prop="upper">
          <el-switch v-model="temp.upper" :active-value="1" :inactive-value="0" active-color="#13ce66" />
        </el-form-item>
        <el-form-item label="图片" prop="productImg">
          <el-input v-model="temp.productImg" placeholder="请上传图片" style="display: none" />
          <img-upload-multiple ref="imgUpload" :imgs="imgs" @onChange="changeImg" extra-tip="，建议尺寸为750×620"></img-upload-multiple>
        </el-form-item>
        <el-form-item label="图文详情" prop="content">
          <tinymce v-model="temp.content" :height="300" />
        </el-form-item>
        <el-button type="primary" @click="saveProduct()" style="margin-left: 100px">
          提交
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { typeList } from '@/api/type'
import { getProduct, saveProduct3 } from '@/api/product'
import { roundPrice } from '@/utils/common'
import waves from '@/directive/waves'
import ImgUploadMultiple from '@/components/ImgUpload/ImgUploadMultiple'
import { isTwoDecimal, isIntegerNature, isTwoDecimalZero } from '@/utils/validate'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'ProductEdit3',
  components: { ImgUploadMultiple, Tinymce },
  directives: { waves },
  data() {
    return {
      formLoading: true,
      temp: {
        productId: undefined,
        productName: '',
        productImg: '',
        productDesc: '',
        productProv: '',
        typeId: undefined,
        originPrice: '',
        deliverPrice: '',
        sales: 0,
        attributes: '',
        tags: '',
        unit: '',
        upper: '',
        content: ''
      },
      imgs: '',
      rules: {
        productName: [{ required: true, message: '请填写商品名', trigger: 'blur' }],
        productDesc: [{ required: true, message: '请填写商品简介', trigger: 'blur' }],
        productImg: [{ required: true, message: '请选择商品图片', trigger: 'change' }],
        productProv: [{ required: true, message: '请填写商品产地省份', trigger: 'blur' }],
        upper: [{ required: true, message: '请选择是否上架', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
        originPrice: [{ required: true, message: '请填写商品消耗积分', trigger: 'blur' }, { validator: isTwoDecimal, trigger: 'blur' }],
        deliverPrice: [{ required: true, message: '请填写运费', trigger: 'blur' }, { validator: isTwoDecimalZero, trigger: 'blur' }],
        sales: [{ required: true, message: '请填写商品销量', trigger: 'blur' }, { validator: isIntegerNature, trigger: 'blur' }],
        attributes: [{ required: true, message: '请填写商品规格类型名称', trigger: 'blur' }],
        unit: [{ required: true, message: '请填写商品售卖单位', trigger: 'blur' }]
      },
      typeList: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  computed: {
    typeMap: function() {
      return this.typeList.reduce((acc, cur) => {
        acc[cur.typeId] = cur.typeName
        return acc
      }, {})
    }
  },
  created() {
    this.getTypeList()
    this.initForm()
  },
  methods: {
    initForm() {
      const productId = this.$route.params.id
      if (productId == 0) {
        console.log('Hello World!')
      } else {
        this.formLoading = true
        getProduct({ productId: productId }).then(response => {
          this.imgs = response.data.productImg
          this.temp = response.data
          this.temp.deliverPrice = this.roundPrice(this.temp.deliverPrice)
          // 消除空格影响
          if (this.temp.tags.replace(/(^\s*)|(\s*$)/g, '') === '' || !this.temp.tags) {
            this.dynamicTags = []
          } else {
            this.dynamicTags = this.temp.tags.substr(1).split('#')
          }
          this.formLoading = false
        })
      }
    },
    getTypeList() {
      typeList(3).then(response => {
        this.typeList = response.data
      })
    },
    saveProduct() {
      const data = Object.assign({}, this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.formLoading = true
          data.deliverPrice = data.deliverPrice * 100
          // 消除空格影响
          if (this.temp.tags.replace(/(^\s*)|(\s*$)/g, '') === '' || !data.tags) {
            data.tags = ''
          }
          saveProduct3(data).then(() => {
            this.$notify({
              title: 'Success',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push({ name: 'Product3' })
            this.formLoading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    changeImg() {
      this.temp.productImg = this.$refs.imgUpload.urls
    },
    roundPrice,
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.temp.tags = this.temp.tags.replace('#' + tag, '')
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.temp.tags = this.temp.tags + '#' + this.inputValue
      this.inputVisible = false
      this.inputValue = ''
    },
    goBack() {
      this.$router.push({
        name: 'Product3'
      })
    }
  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
